<template>
  <div>
    <!-- 筛选项 -->
    <el-row :gutter="20" class="gl_searchBox gl_mb_15">
      <el-col :span="6" :lg="4">
        <p>按机构名称</p>
        <el-input v-model="qo.Filter" placeholder="请输入机构名称" size="mini" clearable @change="getPageList()" />
      </el-col>
      <el-col :span="6" :lg="4">
        <p>按机构等级查找</p>
        <el-select v-model="qo.TypeCodes" size="mini" placeholder="请选择机构等级" filterable @change="getPageList()">
          <el-option v-for="item in organizationUnitsTypesFilter" :key="item.code" :value="item.code" :label="item.name" />
        </el-select>
      </el-col>
      <el-col :span="6" :lg="4">
        <p>按地域划分</p>
        <el-select v-model="qo.CityCode" size="mini" placeholder="请选择下级市" filterable @change="onChangeCity">
          <el-option v-for="item in cityList" :key="item.code" :value="item.code" :label="item.name" />
        </el-select>
      </el-col>
      <el-col :span="6" :lg="4">
        <p />
        <el-select v-model="qo.CountyCode" size="mini" placeholder="请选择下级区/县" filterable @change="getPageList()">
          <el-option v-for="item in countryList" :key="item.code" :value="item.code" :label="item.name" />
        </el-select>
      </el-col>
      <el-col :span="6" :lg="4">
        <p>是否采用全局策略</p>
        <el-select v-model="qo.HasPersonalSetting" size="mini" placeholder="请选择是否采用全局策略" filterable @change="getPageList()">
          <el-option v-for="item in staticDict.HasPersonalSetting" :key="item.code" :value="item.code" :label="item.value" />
        </el-select>
      </el-col>
      <el-col :span="6" :lg="4" class="search_btn">
        <!-- 查询按钮 -->
        <el-button type="primary" size="mini" @click="getPageList()">{{ $t('button.query') }}</el-button>
        <!-- 重置按钮 -->
        <el-button type="warning" size="mini" @click="initForm()">{{ $t('button.Reset') }}</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="tableLoading" :data="tableData" size="mini" stripe class="gl_table_noBorder">
      <el-table-column type="index" label="序号" align="center" width="100" />
      <el-table-column prop="displayName" label="机构名称" min-width="300" />
      <el-table-column prop="typeCode" label="机构等级" width="200">
        <template slot-scope="scope">
          {{ formatTableTypeCode(scope.row.typeCode) }}
        </template>
      </el-table-column>
      <el-table-column label="所属省/市/区县" width="300">
        <template slot-scope="scope">
          {{ scope.row.provinceName }} {{ scope.row.cityName ? '/'+ scope.row.cityName : '' }}  {{ scope.row.countyName ? '/'+ scope.row.countyName : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="hasPersonalSetting" label="是否采用全局策略" align="center" width="300">
        <template slot-scope="scope">
          {{ formatTableHasPersonalSetting(scope.row.hasPersonalSetting) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="editOrgAuth(scope.row)">{{ $t('button.edit') }}</el-button>
          <el-button type="text" size="mini" @click="resetOrgAuth(scope.row)"><span class="gl_color_warning">{{ $t('button.Reset') }}</span></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div align="center" class="gl_py_10">
      <el-pagination
        :current-page="qo.Page"
        :page-size="qo.maxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </div>

    <!-- 模态框，修改 -->
    <el-dialog
      title="编辑"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="880px"
    >
      <div class="orgAuth_customConfig">
        <el-table v-loading="customConfigTableLoading" class="gl_table_noBorder" size="mini" :data="currentOrgCustomSetting" style="width: 100%">
          <el-table-column prop="date" label="发布赛事机构等级">
            <template>
              <span>{{ formatTableTypeCode(currentOrgRow.typeCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="需审核的赛事认证等级" width="180">
            <template slot-scope="scope">
              <div v-for="item in scope.row" :key="item.id">
                <span>{{ item.trainningLevel.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="参与审核机构等级">
            <template slot-scope="scope">
              <div v-for="item in scope.row" :key="item.id">
                <el-checkbox v-model="item.isNeedProvinceApprove">省级</el-checkbox>
                <el-checkbox v-model="item.isNeedCityApprove" :disabled="!item.isCityApproveChangeable">市级</el-checkbox>
                <el-checkbox v-model="item.isNeedCountyApprove" :disabled="!item.isCountyApproveChangeable">县/区级</el-checkbox>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        <el-button :disabled="customConfigTableLoading && !currentOrgCustomSetting.length" type="primary" size="mini" @click="submitEditPersonalSettings">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
// import { CopyData } from '@/lib';

import {
  api_GET_Provinces,
  api_GET_CitiesProvinceCode,
  api_GET_CountiesCityCode
} from '@/extend/api/gameswaggerApi/district.js';

import {
  api_GET_TrainTrainningApproveSettingTrainningApproveUnits, // 获取个性化设置组织机构
  api_DELETE_TrainTrainningApproveSettingPersonalSettingsUnitId, // 删除指定组织的个性化设置
  api_GET_TrainTrainningApproveSettingPersonalSettingsOrganizationId, // 获取某个机构的个性化设置；如果没有，返回该机构等级的全局设置；如果没有全局设置，返回默认设置
  api_POST_TrainTrainningApproveSettingSetPersonalSettings // 新建或修改个性化设置
} from '@/extend/api/trainswaggerApi/app.js';

import {
  Api_GET_TrainTrainningApproveSettingTrainningApproveUnitsQO
} from '@/lib/form/train/swaggerForm.js';

export default {
  props: {
    teamInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    organizationUnitsTypes: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data () {
    return {
      provinceCode: '',
      provincesList: [], // 省
      cityCode: '',
      cityList: [], // 市
      countryList: [], // 区县
      qo: {},
      tableLoading: false, // 表格loading
      tableData: [], // 表格数据
      totalPage: 0, // 总数
      staticDict: { // 静态字典
        HasPersonalSetting: [
          { code: '', value: '全部' },
          { code: false, value: '是' },
          { code: true, value: '否' }
        ]
      },
      dialogVisible: false,
      currentOrgRow: {},
      currentOrgCustomSetting: [],
      customConfigTableLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      dictAll: state => state.dict.dictAll,
      cache: state => state.dict.cache
    }),
    organizationUnitsTypesFilter() {
      // 需要被忽略的字典表 code: 'name'
      const ignoreMap = {
        WXCenter: '无锡中心',
        ChinaTA: '中跆协',
        TA: '协会'
      };
      const _list = this.organizationUnitsTypes.filter(item => !(item.code in ignoreMap));
      _list.unshift({ code: '', name: '全部' });
      return _list;
    }
  },
  watch: {
    teamInfo: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.provinceCode) {
          this.provinceCode = val.provinceCode;
          this.initForm();
        }
      }
    },
    provinceCode (val) {
      if (val) {
        this.apiGetCitiesByProvince();
      }
    },
    cityCode (val) {
      if (val) {
        this.apiGetCountiesByCity();
      } else {
        // this.countryList = [{ code: '', name: '全部' }];
        this.countryList = [];
        this.qo.countryCode = '';
      }
    },
    dialogVisible (val) {
      if (val === false) {
        this.currentOrgRow = {};
        this.currentOrgCustomSetting = [];
      }
    }
  },
  created() {
    this.apiGetProvinces();
    if (this.provinceCode) {
      this.apiGetCitiesByProvince();
    }
  },
  methods: {
    // 初始化
    initForm() {
      this.cityCode = '';
      const _qo = new Api_GET_TrainTrainningApproveSettingTrainningApproveUnitsQO();
      _qo.HasPersonalSetting = '';
      _qo.ProvinceCode = this.teamInfo.provinceCode;
      this.qo = _qo;
      this.countryList = [];
      this.getPageList();
    },
    // 获取表格数据
    getPageList (page) {
      this.tableLoading = true;
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      api_GET_TrainTrainningApproveSettingTrainningApproveUnits(this.qo)
        .then(
          res => {
            this.tableLoading = false;
            this.totalPage = res.totalCount;
            this.tableData = res.items;
            console.log('getPageList -> res', res);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.tableData = [];
            this.totalPage = 0;
            this.$message({
              message: `列表获取失败，${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 表格行重置按钮，删除指定组织的个性化设置
    resetOrgAuth (row) {
      this.$confirm(`重置后将应用全局策略，确定重置【${row.displayName}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.delOrgCustonSetting(row.id);
          }
        );
    },
    // 删除指定组织的个性化设置
    delOrgCustonSetting (id) {
      api_DELETE_TrainTrainningApproveSettingPersonalSettingsUnitId(id)
        .then(
          res => {
            this.getPageList(this.qo.Page);
            this.$message({
              message: `重置成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.$message({
              message: `重置失败，${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 点击编辑按钮，获取某个机构的个性化设置
    editOrgAuth (row) {
      this.currentOrgRow = row;
      this.getOrgCustomSetting(row.id);
      this.dialogVisible = true;
    },
    // 获取某个机构的个性化设置
    getOrgCustomSetting (id) {
      this.customConfigTableLoading = true;
      api_GET_TrainTrainningApproveSettingPersonalSettingsOrganizationId(id)
        .then(
          res => {
            this.customConfigTableLoading = false;
            this.currentOrgCustomSetting = [res];
            console.log('getOrgCustomSetting -> res', res);
          }
        )
        .catch(
          error => {
            this.customConfigTableLoading = false;
            this.currentOrgCustomSetting = [];
            this.$message({
              message: `设置获取失败，${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    /* 确定新建或修改个性化设置 */
    submitEditPersonalSettings () {
      const _vo = {
        unitId: this.currentOrgRow.id,
        trainningApproveSettings: this.currentOrgCustomSetting[0]
      };
      this.customConfigTableLoading = true;
      api_POST_TrainTrainningApproveSettingSetPersonalSettings(_vo)
        .then(
          res => {
            this.$message({
              message: `编辑成功！`,
              type: 'success',
              showClose: true
            });
            this.getPageList(this.qo.Page);
            this.dialogVisible = false;
            this.customConfigTableLoading = false;
          }
        )
        .catch(
          error => {
            this.customConfigTableLoading = false;
            this.$message({
              message: `编辑失败，${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 过滤条件按地域划分 city 发生改变
    onChangeCity (val) {
      this.cityCode = val;
      this.getPageList();
    },
    // 获取 Provinces 字典
    apiGetProvinces () {
      api_GET_Provinces()
        .then(
          res => {
            console.log('apiGetProvinces -> res', res);
          }
        )
        .catch(
          error => {
            console.log('Provinces获取失败' + error.error.message);
          }
        );
    },
    // 获取 Cities 字典
    apiGetCitiesByProvince () {
      api_GET_CitiesProvinceCode(this.provinceCode)
        .then(
          res => {
            res.unshift({ code: '', name: '全部' });
            this.cityList = res;
          }
        )
        .catch(
          error => {
            console.log('Cities获取失败' + error.error.message);
          }
        );
    },
    // 获取 Counties 字典
    apiGetCountiesByCity () {
      api_GET_CountiesCityCode(this.cityCode)
        .then(
          res => {
            res.unshift({ code: '', name: '全部' });
            this.countryList = res;
          }
        )
        .catch(
          error => {
            console.log('Counties获取失败' + error.error.message);
          }
        );
    },
    // 处理表格中得字典数据
    formatTableHasPersonalSetting (data) {
      const _dataType = typeof data;
      let _returnStr = '';
      if (_dataType === 'boolean') {
        _returnStr = data ? '否' : '是';
      }
      return _returnStr;
    },
    // 处理表格中得字典数据
    formatTableTypeCode (data) {
      // console.log('formatTableTypeCode -> data', data);
      let _returnStr = '';
      const _findResult = this.organizationUnitsTypes.find(item => item.code === data);
      if (_findResult) {
        _returnStr = _findResult.name;
      }
      return _returnStr;
    },
    // 分页处理
    sizeChange(MaxResultCount) {
      this.qo.MaxResultCount = MaxResultCount;
      this.getPageList();
    },
    pageIndexChange(currentPage) {
      this.getPageList(currentPage);
    }
  }
};
</script>

<style>
.orgAuth_customConfig .el-table,
.orgAuth_customConfig .el-table__body-wrapper {
  min-height: auto;
}
</style>
